<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类型名称" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入类型名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="首字母" prop="typeFirstChar">
        <el-input
          v-model="queryParams.typeFirstChar"
          placeholder="请输入首字母"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否为黑袋" prop="isOtherBox" label-width="100px">
        <el-select v-model="queryParams.isOtherBox" placeholder="请选择是否为黑袋" clearable>
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:boxType:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['service:boxType:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['service:boxType:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['service:boxType:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tableRef" v-loading="loading" :data="boxTypeList" @selection-change="handleSelectionChange" @row-dblclick="handleRowDbClick">
      <el-table-column type="index" label="" align="center"  width="50" />
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="类型名称" align="center" prop="typeName" />
      <el-table-column label="首字母" align="center" prop="typeFirstChar" />
      <el-table-column label="最大容量(万)" align="center" prop="maxCapability" />
      <el-table-column label="是否为黑袋" align="center" prop="isOtherBox">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isOtherBox"/>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改款箱类型对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" draggable append-to-body>
      <el-form ref="boxTypeRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="类型名称" prop="typeFirstChar">
          <el-input v-model="form.typeName" placeholder="请输入首字母" />
        </el-form-item>
        <el-form-item label="首字母" prop="typeFirstChar">
          <el-input v-model="form.typeFirstChar" placeholder="请输入首字母" />
        </el-form-item>
        <el-form-item label="最大容量(万)" prop="maxCapability">
          <el-input v-model="form.maxCapability" placeholder="请输入最大容量" />
        </el-form-item>
        <el-form-item label="是否为黑袋" prop="isOtherBox">
          <el-select v-model="form.isOtherBox" placeholder="请选择是否为黑袋">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="String(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BoxType">
import { ref, watch } from 'vue'
import { listBoxType, getBoxType, delBoxType, addBoxType, updateBoxType } from "@/api/service/boxType"
import { handleSingleSelection, handleSelectionHighlight } from "@/api/common"

const props = defineProps({
  isModal: {
    type: Boolean,
    default: true
  },
  center: {
    type: Boolean,
    default: true
  },
  // 添加选中项属性
  selectedType: {
    type: Object,
    default: null
  }
})

const { proxy } = getCurrentInstance()
const { sys_yes_no } = proxy.useDict('sys_yes_no')

const boxTypeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const currentSelected = ref({})
const tableRef = ref(null)

const emit = defineEmits(['select'])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    typeName: null,
    typeFirstChar: null,
    maxCapability: null,
    isOtherBox: null,
  },
  rules: {
    typeName: [
      { required: true, message: "类型名称不能为空", trigger: "blur" }
    ],
    typeFirstChar: [
      { required: true, message: "首字母不能为空", trigger: "blur" }
    ],
    maxCapability: [
      { required: true, message: "最大容量(万)不能为空", trigger: "blur" }
    ],
    isOtherBox: [
      { required: true, message: "是否为黑袋不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询款箱类型列表 */
function getList() {
  loading.value = true
  listBoxType(queryParams.value).then(response => {
    boxTypeList.value = response.rows
    total.value = response.total
    loading.value = false
    
    // 数据更新后也要检查是否需要选中某行
    handleSelectionHighlight(tableRef, boxTypeList.value, currentSelected.value)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    typeName: null,
    typeFirstChar: null,
    maxCapability: null,
    isOtherBox: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("boxTypeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据（实现单选行为）
function handleSelectionChange(selection) {
  // 使用通用函数处理单选逻辑
  const result = handleSingleSelection(selection, tableRef.value);
  
  ids.value = result.selectedItems;
  single.value = !result.isSingle;
  multiple.value = result.isEmpty;
  currentSelected.value = result.selectedItem;
}

// 双击行事件
function handleRowDbClick(row) {
  currentSelected.value = row
  if (!props.isModal) {
    emit('select', row)
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加款箱类型"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getBoxType(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改款箱类型"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["boxTypeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBoxType(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBoxType(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除款箱类型编号为"' + _ids + '"的数据项？').then(function() {
    return delBoxType(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/boxType/export', {
    ...queryParams.value
  }, `boxType_${new Date().getTime()}.xlsx`)
}

// 确认选择
function handleSelectConfirm() {
  if (Object.keys(currentSelected.value).length > 0) {
    emit('select', currentSelected.value)
  }
  else {
    // 如果没有选中任何项，显示提示信息
    proxy.$modal.msgWarning("请先选择一条数据")
  }
}

// 监听款箱类型列表变化，如果当前有选中项，则自动选中表格中的对应行
watch(boxTypeList, (newList) => {
  handleSelectionHighlight(tableRef, newList, currentSelected.value)
})

// 监听selectedType属性变化
watch(() => props.selectedType, (newVal) => {
  if (newVal) {
    currentSelected.value = newVal
  }
})

// 监听currentSelected变化，确保表格选中状态更新
watch(currentSelected, (newVal) => {
  if (newVal && newVal.id && boxTypeList.value.length > 0 && tableRef.value) {
    handleSelectionHighlight(tableRef, boxTypeList.value, newVal)
  }
})

getList()

// 向外暴露方法
defineExpose({
  handleSelectConfirm,
  currentSelected
})
</script>

<!-- 全局设置el-input宽度 -->
<style scoped>
:deep(.el-input),
:deep(.el-select .el-input) {
  width: 215px;
  box-sizing: border-box;
}
</style>